import { useUserStore } from '@/stores'
import axios from 'axios'
import { ZlMessage } from './message'

const baseURL = '/dev-api'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL,
  timeout: 100000
})

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()

    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => {
    Promise.reject(err)
  }
)

service.interceptors.response.use(
  (res) => {
    const code = res.data.code
    const msg = res.data.msg
    // 用户 token 过期
    if (code === 3001) {
      ZlMessage.error(msg)
      const userStore = useUserStore()
      userStore.exit()
      return Promise.reject(new Error(msg))
    } else if (code !== 1000) {
      ZlMessage.error(msg)
      return Promise.reject(new Error(msg))
    } else {
      return Promise.resolve(res.data)
    }
  },
  (err) => {
    return Promise.reject(err)
  }
)

export { baseURL }

export default service
